package com.hosever.core;

import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.hosever.utils.SeverStringUtils;

public abstract class AbstractController<E extends AbstractModel,S extends AbstractService<E>> {
	
	@Autowired
	protected S service;
	
	@Autowired
	protected HttpServletRequest request;
	
	private static final Map<Class<?>, String> controllerPathMapping = new ConcurrentHashMap<Class<?>, String>();
	
	protected static String CONTROLLER_REDIRECT = "redirect:";

	
	@ModelAttribute
	private void init(Model model,HttpSession session){
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		session.setAttribute("context", request.getContextPath());
		session.setAttribute("resourcePath", request.getContextPath()+"/resources");
//		model.addAttribute("context", request.getContextPath());
//		model.addAttribute("resourcePath",request.getContextPath()+"/resources");
	}
	
	protected String getRelativePath(String path) {
		Class<?> clz = getClass();
		String controllerPath = controllerPathMapping.get(clz);
		if (controllerPath == null) {
			Class<?> top = clz;
			RequestMapping mappings = null;
			while (top != Object.class) {
				mappings = top.getAnnotation(RequestMapping.class);
				if (mappings != null) {
					break;
				}
				top = top.getSuperclass();
			}
			if (mappings != null) {
				controllerPath = mappings.value()[0];
			} else {
				controllerPath = SeverStringUtils.EMPTY;
			}
			controllerPathMapping.put(clz, controllerPath);
		}
		return controllerPath + path;
	}
}
